<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card >
      <el-row>
        <el-col>
            <el-button type='primary' class='addroles' @click='addRoles'>添加角色</el-button>
        </el-col>
      </el-row>
      <el-dialog
        title="添加角色"
        :visible.sync="addRoleDialogVisible"
        width="40%" @close='closeAddDialog'>
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName" ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDialogRoles()">确 定</el-button>
        </span>
      </el-dialog>
      <el-table :data="rolesList" border stripe row-key='id'>
          <!-- 展开列 -->
        <el-table-column type="expand" label="">
            <template slot-scope="scope">
                <el-row class="vcentre" :class="['borderbottom', index1==0 ? 'bordertop' : '']"  v-for=" (item1,index1) in scope.row.children" :key='item1.id'>
                  <el-col :span='5'><el-tag>{{item1.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                  <el-col :span='19'>
                      <el-row class="vcentre" :class="[ index2==0 ? '' : 'bordertop']"  v-for="(item2,index2) in item1.children" :key='item2.id'>
                          <el-col :span='6'> <el-tag type='danger'>{{item2.authName}}</el-tag><i class="el-icon-caret-right"></i></el-col>
                          <el-col :span='18'>
                              <el-tag @close='removeTagById(scope.row,item3.id)' closable v-for="(item3) in item2.children" :key='item3.id' type='success'>{{item3.authName}}</el-tag>
                          </el-col>
                      </el-row>
                  </el-col>
                </el-row>
                <!-- <pre>{{scope.row}}</pre> -->
            </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width='290px'>
            <template slot-scope="scope">
                    <el-button type='primary' size='mini' icon='el-icon-edit' @click="editRoles(scope.row.id)">编辑</el-button>
                    <el-button type='danger'  size='mini' icon='el-icon-delete' @click="deleteRoles(scope.row.id)">删除 </el-button>
                    <el-button type='warning' size='mini' icon='el-icon-setting' @click="showSetRightsDialog(scope.row)">分配权限</el-button>
            </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 编辑角色对话框 -->
      <el-dialog
        title="编辑角色"
        :visible.sync="editRolesDialogVisible"
        width="40%" @close='closeEditRolesDialog'>
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName" ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editRolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editDialogRoles()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="showSetRightsDialogVisible"
        width="30%" @close='setRightDialogClose()'>
      <el-tree
      :data="rightsList"
      :props="treeProps"
      show-checkbox
      default-expand-all
      node-key='id'
      :default-checked-keys='defaultKeys'
      ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showSetRightsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotRights()">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      //   所有角色下拉列表
      rolesList: [],
      addRoleDialogVisible: false,
      //   表格的数据
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [
          { required: true, message: '必填角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度为3-10', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '必填描述', trigger: 'blur' },
          { min: 4, max: 10, message: '长度为4-10', trigger: 'blur' }
        ]
      },
      editRolesDialogVisible: false,
      //   保存编辑对话框的数据
      editForm: {},
      editFormRules: {
        roleName: [
          { required: true, message: '必填角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度为3-10', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '必填描述', trigger: 'blur' },
          { min: 4, max: 10, message: '长度为4-10', trigger: 'blur' }
        ]
      },
      // 控制分配权限对话框
      showSetRightsDialogVisible: false,
      // 所有权限列表
      rightsList: [],
      // 树形控件的设置
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //  树形控件 默认勾选的数组
      defaultKeys: [],
      // 即将分配权限的角色id
      roleId: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('请求失败')
      }
      this.rolesList = res.data
      console.log(res.data)
    },
    addRoles () {
      this.addRoleDialogVisible = true
    },
    // 关闭添加角色对话框
    closeAddDialog () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加角色
    async addDialogRoles () {
      this.$refs.addFormRef.validate(async valid => {
        //  如果失败
        if (!valid) return
        // 否则请求数据
        const { data: res } = await this.$http.post('roles', this.addForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addRoleDialogVisible = false
        this.getRolesList()
      })
    },
    // 关闭编辑角色对话框
    closeEditRolesDialog () {
      this.$refs.editFormRef.resetFields()
    },
    // 根据id编辑角色
    async editRoles (id) {
      this.editRolesDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('请求失败')
      this.editForm = res.data
      this.editRolesDialogVisible = true
      console.log(this.editForm.roleId)
    },
    // 编辑角色对话框
    async editDialogRoles () {
      this.$refs.editFormRef.validate(async valid => {
      //  如果失败
        if (!valid) return
        // 否则请求数据
        const { data: res } = await this.$http.put('roles/' + this.editForm.roleId, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.$message.success('修改成功')
        this.editRolesDialogVisible = false
        this.getRolesList()
      })
    },
    // 删除角色
    deleteRoles (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('roles/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getRolesList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 根据id删除标签
    removeTagById (row, rightId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${row.id}/rights/${rightId}`)
        if (res.meta.status !== 200) {
          return this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }
        // 为data的第二层children重新赋值，不会刷新列表
        row.children = res.data
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 展示分配权限对话框
    async showSetRightsDialog (role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限列表失败')
      //   this.$message.success('获取权限列表成功')
      this.rightsList = res.data
      console.log(this.rightsList)
      this.getLeafKeys(role, this.defaultKeys)
      this.showSetRightsDialogVisible = true
      this.roleId = role.id
    },
    // 通过递归 获取角色下的所有三级权限的id，保存defaultKeys数组
    getLeafKeys (node, arr) {
      // 如果node节点不包含children就是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果node节点不是三级节点 > 递归函数
      node.children.forEach(element => {
        this.getLeafKeys(element, arr)
      })
    },
    // 关闭对话框重置默认勾选的数组 不会造成数组内容过多
    setRightDialogClose () {
      this.defaultKeys = []
    },
    // 分配权限
    async allotRights () {
    //   获取id 包含选中和半选中
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      // 以,拼接字符串
      const keysStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keysStr })
      if (res.meta.status !== 200) return this.$message.error('角色授权失败')
      this.$message.success('角色授权成功')
      this.getRolesList()
      this.showSetRightsDialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
.addroles {
    margin-bottom: 20px;
}
.el-tag {
    margin: 10px;
}
.bordertop {
    border-top: 1px solid #eee;
}
.borderbottom {
    border-bottom: 1px solid #eee;
}
.vcentre {
    display: flex;
    align-items: center;
}
</style>
